import axios,{AxiosRequestConfig,AxiosResponse} from "axios"

const defaultConfig={
  baseUrl:'',
  timeout:5000,
  headers:{
    'domain':'www.xinshenghe999.com'
  }
}

class Http{
  constructor(){
    this.httpInterceptorsReq()
    this.httpInterceptorsRes()
  }

  private static axiosInstance=axios.create(defaultConfig)

  //请求拦截,axios请求的类型是一个axios封装的AxiosRequestConfig
  private httpInterceptorsReq(){
    //需要用class类调用内部的私有变量
    Http.axiosInstance.interceptors.request.use((config)=>{
      return config
    },error=>{
      return Promise.reject(error)
    }
    )
  }

  //响应拦截：axios响应的类型AxiosResponse
  private httpInterceptorsRes(){
    Http.axiosInstance.interceptors.response.use((config:AxiosResponse)=>{
      return config
    },error=>{
      return Promise.reject(error)
    })
  }

  //注意，axios中的get和post响应对象为promise，并且接收一个泛型T
  //封装get
  public httpGet<T>(url:string,params:AxiosRequestConfig): Promise<T>{
    return Http.axiosInstance.get(url,params).then(res=>res.data).catch()
  }
  //封装post
  public httpPost<T>(url:string,params:AxiosRequestConfig): Promise<T>{
    return Http.axiosInstance.post(url,params).then(res=>res.data).catch()
  }
}

export const http=new Http()